<template>
  <div>
    <a-table
      size="small"
      id="ref_table"
      style="max-height: 300px;overflow-y: auto"
      ref="ref_table"
      :columns="columns"
      :dataSource="data"
      :pagination="false"
      :loading="memberLoading"
      :rowKey="(record,index)=> index"
    >
      <!--联系方式-->
      <template slot="contactType" slot-scope="text, record,index ">
        <template v-if="record.editable">
          <a-form :form="form" layout="inline">
            <a-form-item>
              <a-select
                :default-value="text?text:'移动电话'"
                @change="e=>changeContact(e, record.id, 'contactType',index)"
                style="width: 135px;"
                placeholder="联系方式" >
                <a-select-option v-for="(item,index) in CustomerConsult.contactDetails" :key="index" :value="item.id" >{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-form>
        </template>
        <template v-else>{{ text?text:'-' }}</template>
      </template>

      <!--联系号码-->
      <template slot="contactContent" slot-scope="text, record,index">
        <a-form :form="form" layout="inline" v-if="record.editable===true">
          <a-form-item has-feedback>
            <!--移动电话-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901201'"
              :maxLength="11"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: true, message: '' },{validator: validatorPhone}]}]"
              style="width: 165px;"
              placeholder="联系号码"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />
            <!--固定电话-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901202'"
              :maxLength="13"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: true, message: '' },{validator: validatorTel}]}]"
              style="width:165px;"
              placeholder="区号"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />
            <!--传真-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901203'"
              :maxLength="20"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: true, message: '不能为空' },{validator: validatorFax}]}]"
              style="width: 165px;"
              placeholder="传真"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />
            <!--QQ-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901204'"
              :maxLength="11"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: true, message: '不能为空' },{validator: validatorQQ}]}]"
              style="width: 165px;"
              placeholder="QQ号码"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />
            <!--微信号-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901205'"
              :maxLength="20"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: true, message: '不能为空' },{validator: validatorWX}]}]"
              style="width: 165px;"
              placeholder="微信号"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />

            <!--邮箱-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901206'"
              :maxLength="20"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: true, message: '不能为空' },{validator: validatorEmail}]}]"
              style="width: 165px;"
              placeholder="邮箱"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />
            <!--失效-->
            <a-input
              :ref="`input_${current_contact_type}_${index}`"
              v-if="current_contact_type==='0901207'"
              allow-clear
              v-decorator="[`phone${index}`,{rules: [{ required: false}]}]"
              style="width: 165px;"
              placeholder="联系号码"
              @change="e => handleChange(e.target.value, record.id, 'contactContent')"
            />
          </a-form-item>
        </a-form>
        <span v-else>{{ text?text:'-' }}</span>
      </template>

      <!--备注-->
      <template slot="remark" slot-scope="text, record">
        <template v-if="record.editable">
          <a-form :form="form" layout="inline">
            <a-form-item>
              <a-input
                style="margin: -5px 0"
                :value="text"
                placeholder="备注"
                @change="e => handleChange(e.target.value, record.id, 'remark')"
              />
            </a-form-item>
          </a-form>
        </template>
        <template v-else>{{ text?text:'-' }}</template>
      </template>

      <!--操作-->
      <template slot="operation" slot-scope="text, record,index">
        <template v-if="record.editable">
          <span v-if="record.isNew">
            <a @click="saveRow(record,'add',index)">添加</a>
            <a-divider type="vertical" />
            <a @click="remove(record.id)">删除</a>
          </span>
          <span v-else>
            <a @click="saveRow(record,'edit',index)">保存</a>
            <a-divider type="vertical" />
            <a @click="cancel(record.id)">取消</a>
          </span>
        </template>
        <span v-else>
          <a-button class="g-bt-pad-0" v-if="record.isEdit===1" :disabled="editingKey !== ''||add_edit_state===2" type="link" @click="toggle(record,index)">
            编辑
          </a-button>
          <a-button v-else disabled type="link" class="g-bt-pad-0" >编辑过期</a-button>
        </span>
        <a-button
          v-if="netBthPermission && (record.contactType=='移动电话'||record.contactType=='固定电话')"
          class="g-bt-pad-0"
          style="margin-left: 5px;"
          type="link"
          @click="clickCallPhone(record)">
          呼叫
        </a-button>
      </template>

    </a-table>
    <a-button
      class="table-new-add-row"
      :class="add_edit_state===1?'':'table-new-add-row-border'"
      :disabled="add_edit_state===1"
      type="dashed"
      icon="plus"
      @click="newMember">
      新增联系方式
    </a-button>

  </div>

</template>

<script>
import {UpdateContact} from '@/api/customer/customer'
import {getCustomerConsult} from '@/api/customer/customer'
import { callPhone } from '@/api/components/callPhone'
import Bus from '@/utils/bus'
import { mapState } from 'vuex'
export default {
  name: 'ContactTable',
  props: {
    ContactList:{
      type:Array,
      default:()=>[]
    },
    customerId:{
      type:String,
      default:''
    },
    customer:{
      type:Object,
      default:()=>{}
    },
  },
  data() {
    return {
      call_res:{},
      editingKey:'',
      default_contact_type:'0901201',
      current_contact_type:'0901201',
      form: this.$form.createForm(this),
      CustomerConsult: { //客户咨询下拉系列
        contactDetails : [],//联系方式
      },
      operation_type:'edit',
      memberLoading: false,
      columns: [
        { title: '联系方式', dataIndex: 'contactType', key: 'contactType', width: '17%', scopedSlots: { customRender: 'contactType' } },
        { title: '联系号码', dataIndex: 'contactContent', key: 'contactContent', width: '20%', scopedSlots: { customRender: 'contactContent' } },
        { title: '备注', dataIndex: 'remark', key: 'remark', width: '17%', scopedSlots: { customRender: 'remark' } },
        { title: '登记人', dataIndex: 'recorder', key: 'recorder', width: '13%', scopedSlots: { customRender: 'recorder' } },
        { title: '登记时间', dataIndex: 'recordDate', key: 'recordDate', width: '17%', scopedSlots: { customRender: 'recordDate' } },
        { title: '操作', key: 'action', scopedSlots: { customRender: 'operation' },width: 150 }
      ],
      data: [],
      add_edit_state:0,
    }
  },
  watch:{
    ContactList(val){
      this.data=val
      this.data=this.data.map(item=>({...item,editable:false}))
      // console.log('子组件接受的联系方式数据',this.data)
    },
    customerId(val){
      return val
    },
    customer(val){
      return val
    }
  },
  created() {
    /**
     下拉接口集合
     * */
    getCustomerConsult().then(res => {
      // console.log('联系方式接口',res)
      this.CustomerConsult = res
    })
  },
  computed:{
    ...mapState({
      equipment_status:state=>state.phoneBox.equipment.status,
      connect_status:state=>state.phoneBox.connect.status,
    }),
    //新增电网按钮查看权限
    netBthPermission(){
      const admintype = this.$store.state.user.admintype
      if(admintype===1){
        return true
      }
      if(this.hasPerm('customer:netConsultation:list')){
        return true
      }
      return false
    }
  },

  methods: {
    /**
    拨打电话
     * */
    clickCallPhone(record){
      if(!this.connect_status||!this.equipment_status){
        this.$message.info('未连接设备')
        return
      }
      const contactContent = record.contactContent
      const name = this.customer.name
      const customerId = record.customerId
      const ccid =window.localStorage.getItem('ccid')
      const params={
        sendTel:contactContent,
        customerName:name,
        customerId:	customerId,
        ccid:ccid
      }
      callPhone(params).then(res=>{
        console.log('拨打电话结果为',res)
        const data= res.data
        this.$store.commit('phoneBox/setCustomer',data)
        if(!data.switchCard){
          Bus.$emit('OnDial', {contactContent,type:false} )
        }else{
          Bus.$emit('OnCBSwitchNext')
          setTimeout(()=>{
            Bus.$emit('OnDial', {contactContent,type:false} )
          },1000)
        }
      })
    },
    /**
     表单校验手机号
     * */
    validatorPhone (rule, value, callback) {
      if(!(/^1[3456789]\d{9}$/.test(value))){
        callback('必须为11位数字！')
      }
      callback()
    },
    /**
     表单校验固定电话
     * */
    validatorTel (rule, value, callback) {
      const reg = /^(\d{3,4}-)?\d{7,8}$/
      if (!reg.test(value)) {
        callback('格式不正确')
      }
      callback()
    },
    /**
     表单校验QQ号码
     * */
    validatorQQ (rule, value, callback) {
      const reg = /^[1-9][0-9]{4,10}$/gim
      if (!reg.test(value)) {
        callback('必须为5-11位')
      }
      callback()
    },
    /**
     表单校验微信号
     * */
    validatorWX (rule, value, callback) {
      const reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
      if (!reg.test(value)) {
        callback('请填写正确的微信号！')
      }
      callback()
    },
    /**
     表单校验传真
     * */
    validatorFax (rule, value, callback) {
      // const reg = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
      const reg = /^(\d{3,4}-)?\d{7,8}$/
      if (!reg.test(value)) {
        callback('格式不正确')
      }
      callback()
    },
    /**
     表单校验邮箱
     * */
    validatorEmail (rule, value, callback) {
      const reg = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
      if (!reg.test(value)) {
        callback('邮箱格式不正确')
      }
      callback()
    },
    /**
     新增一行
     * */
    newMember () {
      this.add_edit_state=2
      this.current_contact_type=this.default_contact_type

      const len =this.data.length
      if(len>0&&this.data[len-1].isNew){
        this.$message.warning('当前新增记录已存在！')
        return
      }
      // this.$refs.contact_table_ref.scrollIntoView()
      this.operation_type='add'
      this.data.push({
        id: '',
        editable: true,
        isNew: true,
        contactContent: '',
        contactType: '',
        remark: null,
        clientId:'',
        recorder:'',
        recordDate:'',
      })
      this.$nextTick(()=>{
        const container = document.getElementById('ref_table') // 获取对象
        container.scrollTop = container.scrollHeight // 滚动高度
        // this.$refs.ref_table.scrollTop = this.$refs.ref_table.scrollHeight
      })
    },
    /**
     改变联系方式
     * */
    changeContact(value,id, column,index){
      console.log('改变联系方式',value)
      this.current_contact_type=value
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      const contactContent=target.contactContent
      if (target) {
        target[column] = value
        this.data = newData
      }
      let message= ''
      let error_flag =false
      switch (value){
        case '0901201':
          //移动电话
          const reg_phone = /^1[3456789]\d{9}$/
          if(!reg_phone.test(contactContent)){
            message = '必须为11位数字！'
            error_flag=true
          }
          break
        case '0901202':
          //固定电话
          const reg_tel = /^(\d{3,4}-)?\d{7,8}$/
          if(!reg_tel.test(contactContent)){
            message = '固定电话格式不正确！'
            error_flag=true
          }
          break
        case '0901203':
          //传真
          const reg_Fax = /^(\d{3,4}-)?\d{7,8}$/
          if(!reg_Fax.test(contactContent)){
            message = '传真格式不正确！'
            error_flag=true
          }
          break
        case '0901204':
          //QQ
          const reg_QQ = /^[1-9][0-9]{4,10}$/gim
          if(!reg_QQ.test(contactContent)){
            message = '必须为5-11位！'
            error_flag=true
          }
          break
        case '0901205':
          //微信
          const reg_wechat = /^[a-zA-Z]([-_a-zA-Z0-9]{5,19})+$/
          if(!reg_wechat.test(contactContent)){
            message = '微信格式不正确！'
            error_flag=true
          }
          break
        case '0901206':
          //邮箱
          const reg_email = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/
          if(!reg_email.test(contactContent)){
            message = '邮箱格式不正确！'
            error_flag=true
          }
          break
      }
      if(contactContent&&error_flag){
        this.form.setFields({
          [`phone${index}`]:{
            errors:[{ message:message, field: `phone${index}`}],
            value:contactContent
          }
        })
        return
      }
      this.form.setFields({
        [`phone${index}`]:{
          value:contactContent
        }
      })
    },
    handleChange (value, id, column) {
      const newData = [...this.data]
      const target = newData.find(item => id === item.id)
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    remove (id) {
      const newData = this.data.filter(item => item.id !== id)
      this.data = newData
      this.add_edit_state=0
    },
    /**
     保存数据
     * */
    saveRow (record,type,index) {
      // 是否有导医权限
      if(!this.hasPerm('receive:receiveList')){
        this.$message.info("无导医权限!")
        return 
      }
      const { form: { validateFields } } = this
      validateFields((errors, values) => {
        if (errors) {
          console.log('表单检验未通过111',errors)
          return
        }
        console.log('表单检验通过222',values)
        this.memberLoading = true
        const { id } = record
        const target = this.data.find(item => item.id === id)
        const contactObj=this.CustomerConsult.contactDetails.find(item => item.name === target.contactType)
        const contactType =contactObj?contactObj.id:target.contactType
        let parmas
        if(type=='edit'){
          console.log('编辑')
          parmas={
            id:target.id,
            clientId	:target.customerId,
            contactType	:contactType,
            contactContent:target.contactContent,
            recorder	:target.recorder,
            recordDate	:target.recordDate,
            remark	:target.remark,
          }
        }
        if(type=='add'){
          parmas={
            clientId	:this.customerId,
            contactType	:contactType?contactType:this.default_contact_type,
            contactContent:target.contactContent,
            remark	:target.remark,
          }
          console.log('增加',parmas)
        }
        UpdateContact(parmas).then(res=>{
          console.log('联系方式请求结果为',res)
          if(res.code==200){
            this.$message.success(type=='add'?'添加成功':'修改成功')
            this.$emit('reLoad')
            this.add_edit_state=0
          }else{
            this.$message.info(res.message)
            if(type=='edit'){
              this.cancel(target.id)
              target.editable = false
            }
            this.form.setFields({
              [`phone${index}`]:{
                errors:[{ message: res.message, field: `phone${index}`}]
              }
            })
          }

        }).finally(()=>{
          this.memberLoading = false
          this.editingKey = ''

        })
      })
    },
    //点击编辑
    toggle (record,index) {
      this.add_edit_state=1
      const contactObj=this.CustomerConsult.contactDetails.find(item => item.name === record.contactType)
      this.current_contact_type=contactObj.id
      const id =record.id
      this.editingKey = id
      this.operation_type='edit'
      const target = this.data.find(item => item.id === id)
      this.$nextTick(()=>{
        setTimeout(()=>{
          this.form.setFieldsValue({
            [`phone${index}`]:target.contactContent
          })
        })
      })

      target._originalData = { ...target }
      target.editable = !target.editable

      setTimeout(()=>{
        //光标定位在末尾
        this.$nextTick(()=>{
          const length = target.contactContent.length
          const input_ref = `input_${this.current_contact_type}_${index}`
          this.$refs[input_ref].focus()
        })
      })

    },
    getRowByKey (id, newData) {
      const data = this.data
      return (newData || data).find(item => item.id === id)
    },
    cancel (id) {
      const target = this.data.find(item => item.id === id)
      this.editingKey = ''
      Object.keys(target).forEach(id => { target[id] = target._originalData[id] })
      target._originalData = undefined
      this.add_edit_state=0
    },
  },
}
</script>

<style lang="less" scoped>
 .ant-table-wrapper{
  margin:0 !important;
}
 /deep/ .ant-form-inline .ant-form-item-with-help{
   margin-bottom: -15px;
 }
.table-new-add-row{
  width: 100%;
  margin-top: 24px;
  margin-bottom: 24px;
}
.table-new-add-row-border{
  border-color: #3399ff;color: #3399ff;
}
</style>